const express = require('express');
const jwt = require('jsonwebtoken');
const { expressjwt } = require('express-jwt');

const app = express();
const secretKey = "bbj";

//不需要权限限定访问,api开头的网址不需要token验证
app.use(expressjwt({ secret: secretKey, algorithms: ["HS256"] }).unless({ path: [/^\/api\//] }))


//创建session
app.get('/api/login', (req, res) => {
  //设置token
  const token = jwt.sign({ username: "jack", age: 20 }, secretKey, { expiresIn: '1h' });
  res.send(`登录成功:${token}`)
})

//获取token值
app.post('/admin', (req, res) => {
  console.log(req.auth);
  res.send(`当前用户:${req.auth.username}`);
})

app.listen(3000, () => {
  console.log('正在监听http://localhost:3000')
})